Beautiful arrangement II

Time: O(N); Space: O(1); med

Given two integers N and K, you need to construct a list which contains N different positive integers ranging from 1 to N and obeys the following requirement: Suppose this list is [a1, a2, a3, … , aN], then the list [abs(a1-a2), abs(a2-a3), abs(a3-a4), … , abs(aN-1 - aN)] has exactly K distinct integers.

If there are multiple answers, print any of them.

Example 1:

Input: n = 3, k = 1

Output: [1, 2, 3]

Explanation:

  • The [1, 2, 3] has three different positive integers ranging from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1.

Example 2:

Input: n = 3, k = 2

Output: [1, 3, 2]

Explanation:

  • The [1, 3, 2] has three different positive integers ranging from 1 to 3, and the [2, 1] has exactly 2 distinct integers: 1 and 2.

Note:

  • The N and K are in the range 1 <= K < N <= 10^4.

[1]:
class Solution1(object):
    def constructArray(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[int]
        """
        result = []
        left, right = 1, n
        while left <= right:
            if k % 2:
                result.append(left)
                left += 1
            else:
                result.append(right)
                right -= 1
            if k > 1:
                k -= 1
        return result
[2]:
s = Solution1()
n = 3
k = 1
assert s.constructArray(n, k) == [1, 2, 3]
n = 3
k = 2
assert s.constructArray(n, k) == [1, 3, 2] or [3, 1, 2]